package com.booktrade.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.booktrade.dto.OrderDTO;
import com.booktrade.dto.OrderRequestDTO;
import com.booktrade.dto.OrderStatusDTO;
import com.booktrade.entity.Orders;
import com.booktrade.result.Result;
import com.booktrade.service.*;
import com.booktrade.util.BaseContext;
import com.booktrade.vo.OrderVo;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 订单表，存储用户购买的订单信息 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
public class OrdersController {

    private final IOrdersService orderService;
    private final INotificationsService notificationsService;


    @PostMapping("/save")
    @Operation(summary = "保存订单")
    public Result<List<Integer>> saveOrder(@RequestBody OrderRequestDTO orderRequestDTO) {
        Integer buyerId = BaseContext.getCurrentId();
        List<Integer> list = orderService.saveOrder(orderRequestDTO, buyerId);
        return Result.success(list);

    }

    /**
     * 1) 买家查看自己的订单状态
     */
    @GetMapping("/buyer/orders")
    @Operation(summary = "买家查看自己的订单")
    public Result<List<OrderVo>> getBuyerOrders(OrderStatusDTO statusDTO) {
        Integer buyerId = BaseContext.getCurrentId();
        List<OrderVo> orders = orderService.getOrdersByBuyerId(buyerId,statusDTO.getStatus());
        return Result.success(orders);
    }

    /**
     * 处理订单支付请求
     * 当用户完成支付后，通过此接口更新订单状态为已支付
     *
     * @param orderId 订单ID，用于标识特定的订单
     * @return 返回支付结果，包括支付成功或失败的信息
     */
    @PostMapping("/buyes/{orderId}")
    @Operation(summary = "处理订单支付请求")
    public Result payOrder(@PathVariable("orderId") String orderId) {
        if (orderId == null || orderId.trim().isEmpty()) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        String[] orderIdArray = orderId.split(",");
        for (String s : orderIdArray) {
            try {
                Integer orderIdInt = Integer.parseInt(s);
                // 根据订单ID获取订单详情
                Orders orders = orderService.getById(orderIdInt);
                // 更新订单状态为已支付
                orders.setStatus("已支付");
                // 将更新后的订单信息保存到数据库
                orderService.updateById(orders);
            } catch (NumberFormatException e) {
               throw new IllegalArgumentException("订单ID格式不正确");
            }
        }
        return Result.success();
    }


    @PostMapping("/cancel/{orderId}")
    @Operation(summary = "取消订单支付")
    public Result cancelOrder(@PathVariable("orderId") Integer orderId) {
        // 根据订单ID获取订单详情
        Orders orders = orderService.getById(orderId);
        // 更新订单状态为已支付
        orders.setStatus("订单已取消");
        // 将更新后的订单信息保存到数据库
        orderService.updateById(orders);
        // 返回支付成功的结果
        return Result.success();
    }

    /**
     * 2) 买家确认收货
     */
    @PostMapping("/buyer/confirm/{orderId}")
    @Operation(summary = "买家确认收货")
    public Result<Void> confirmReceipt(@PathVariable Integer orderId) {
        Integer buyerId = BaseContext.getCurrentId();
        boolean success = orderService.confirmReceipt(orderId, buyerId);
        return success ? Result.success() : Result.error("确认收货失败");
    }

    /**
     * 3) 卖家查看自己的订单
     */
    @GetMapping("/seller/orders")
    @Operation(summary = "卖家查看自己的订单")
    public Result<List<OrderVo>> getSellerOrders(OrderStatusDTO statusDTO) {
        Integer sellerId = BaseContext.getCurrentId();
        List<OrderVo> orders = orderService.getOrdersBySellerId(sellerId,statusDTO.getStatus());
        return Result.success(orders);
    }

    /**
     * 4) 卖家发货
     */
    @PostMapping("/seller/ship/{orderId}")
    @Operation(summary = "卖家发货")
    public Result<Void> shipOrder(@PathVariable Integer orderId) {
        Integer sellerId = BaseContext.getCurrentId();
        boolean success = orderService.shipOrder(orderId, sellerId);
        Assert.isTrue(success, "发货失败");
        notificationsService.createNotification(sellerId, "您的订单已发货，请及时确认收货。");
        return Result.success();
    }

    /**
     * 5) 申请退款
     */
    @PostMapping("/buyer/refund/{orderId}")
    @Operation(summary = "买家申请退款")
    public Result<Void> requestRefund(@PathVariable Integer orderId) {
        Integer buyerId = BaseContext.getCurrentId();
        boolean success = orderService.requestRefund(orderId, buyerId);
        return success ? Result.success() : Result.error("申请退款失败");
    }
}
